package com.ht.api.bigtask.impl.qywx;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import com.ht.api.bigtask.BaseBigTask;
import com.ht.api.constant.CustomerLinkStatus;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.open.OpenUtil;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 初始化：获客链接
 * @author asq
 * @createTime 2025年4月2日 08:51:15
 */
@Slf4j
public class QueryCustomerLinkList extends BaseBigTask {
	/** 接口ID：获取获客链接列表 */
	private static final long API_ID_LIST = 1896830019448213504L;
	/** 接口ID：获取获客链接详情 */
	private static final long API_ID_INFO = 1896831578265489408L;
	/** 接口ID：查询链接使用详情 */
	private static final long API_ID_STATISTIC = 1896836500184764416L;

	@Override
	protected void doExecute(String appId, JSONObject context, Entity bean) {
		DataSource ds = getTenantDs(appId);
		StreamLoadConfig streamLoadConfig = DbConfig.getStreamLoadConfigByDataSource(ds);
		String str = OpenUtil.call(appId, API_ID_LIST, JSONUtil.createObj().set("limit", 100));
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			List<Entity> list = new ArrayList<>();
			JSONArray linkArr = obj.getJSONArray("link_id_list");
			
			for (int i = 0; i < linkArr.size(); i++) {
				String linkId = linkArr.getStr(i);
				list.addAll(createCustomerLinkByWwx(appId, linkId));
			}
			
			//System.err.println(">>"+JSONUtil.toJsonPrettyStr(list));
			Db.insertBatchWithStream(streamLoadConfig, list);			
			log.info("[QueryContactWayList]企微初始化，获取联系我列表，总数：{}", linkArr.size());
		} else {
			log.error("[QueryContactWayList]企微初始化，获取联系我列表时返回失败：{}", obj.getStr("errmsg"));
		}
	}
	
	/**
	 * 根据微信返回的linkId创建本地数据库中的Entity
	 * @param appId
	 * @param linkId
	 * @return
	 */
	private List<Entity> createCustomerLinkByWwx(String appId, String linkId) {
		List<Entity> list = new ArrayList<>();
		String str = OpenUtil.call(appId, API_ID_INFO, JSONUtil.createObj().set("link_id", linkId));
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			// 查询获客链接添加的客户信息
			DateTime date30DaysAgo = DateUtil.offsetDay(DateUtil.date(), -30);
			long timestamp30DaysAgo = date30DaysAgo.getTime() / 1000;
			JSONObject param = JSONUtil.createObj();
			param.set("link_id", linkId);
			param.set("start_time", timestamp30DaysAgo);
			param.set("end_time", DateUtil.currentSeconds());
			String str2 = OpenUtil.call(appId, API_ID_STATISTIC, param);
			JSONObject obj2 = JSONUtil.parseObj(str2);
			
			// 企微获客链接详情
			JSONObject link = obj.getJSONObject("link");
			JSONObject priorityOption = obj.getJSONObject("priority_option");
			JSONObject range = obj.getJSONObject("range");
			
			// 获客链接主表
			Entity wxCustomerLink = Db.createEntity("wx_customer_link");
			wxCustomerLink.set("appid", appId);
			wxCustomerLink.set("link_id", linkId);
			wxCustomerLink.set("link_name", link.getStr("link_name"));
			wxCustomerLink.set("status", CustomerLinkStatus.ENABLED);
			wxCustomerLink.set("url", link.getStr("url"));
			wxCustomerLink.set("skip_verify", link.getBool("skip_verify") ? 1 : 0);
			
			if (obj2.getInt("errcode") == 0) {
				wxCustomerLink.set("click_link_customer_cnt", obj2.getInt("click_link_customer_cnt"));		
				wxCustomerLink.set("new_customer_cnt", obj2.getInt("new_customer_cnt"));		
			}
			
			if (priorityOption != null) {
				wxCustomerLink.set("priority_type", priorityOption.getInt("priority_type"));
				JSONArray priorityUseridList = priorityOption.getJSONArray("priority_userid_list");
				wxCustomerLink.set("priority_userid_list", priorityUseridList.toString());
				if (!priorityUseridList.isEmpty()) {
					String hashCodes = priorityUseridList.stream().map(s -> String.valueOf(Math.abs(s.hashCode())))
							.collect(Collectors.joining(","));
					wxCustomerLink.set("priority_userid_list_hash", hashCodes);
				}
			}
			
			wxCustomerLink.set("click_link_customer_cnt", 0);
			wxCustomerLink.set("new_customer_cnt", 0);
			wxCustomerLink.set("error", 0);
			
			JSONArray userArr = range.getJSONArray("user_list");
			if (!userArr.isEmpty()) {
				wxCustomerLink.set("user_list", userArr.toString());
				String hashCodes = userArr.stream().map(s -> String.valueOf(Math.abs(s.hashCode())))
						.collect(Collectors.joining(","));
				wxCustomerLink.set("user_hash", hashCodes);
			}
			list.add(wxCustomerLink);
			
			// 创建关联表
			for (int i = 0; i < userArr.size(); i++) {
				String userid = userArr.getStr(i);

				Entity wxCustomerLinkRelation = Db.createEntity("wx_customer_link_relation");
				wxCustomerLinkRelation.set("link_main_id", wxCustomerLink.getMainId());
				wxCustomerLinkRelation.set("link_id", linkId);
				wxCustomerLinkRelation.set("userid", userid);
				wxCustomerLinkRelation.set("create_time", DateUtil.now());
				wxCustomerLinkRelation.set("friend_cnt", 0);
				wxCustomerLinkRelation.set("status", 0);
				list.add(wxCustomerLinkRelation);
			}
		} else {
			log.error("[QueryContactWayList]企微初始化，获取联系我详情时返回失败：{}", obj.getStr("errmsg"));
		}
		return list;
	}

}
